
const actions = {
    add(context,val){
        console.log('增加购物车',val)
        //遍历carList获取有没有carList[i].name与val.name相同的值
        let carList=context.state.carList
        for(let i = 0;i < carList.length;i++){
            if(carList[i].name === val.name){
                context.commit('addNumCar',i)
                return
            }
        }
        context.commit('addCar',{
            name:val.name,
            price:val.price,
            num:1
        })


    },

}
const mutations = {
    changePrice(state,val){
        console.log('改变价格',val)
        state.spList[val.index].price=val.newPrice
        for(let i = 0;i < state.carList.length;i++){
            if(state.carList[i].name === val.name){
                state.carList[i].price = val.newPrice
                return
            }
        }

    },
    addNumCar(state,val){
        console.log('增加数量',val)
        state.carList[val].num += 1
    },
    dropNumCar(state,val){
        console.log('减少数量',val)
        state.carList[val].num -= 1
    },
    addCar(state,val){
        console.log('增加购物车商品',val)
        state.carList.push(val)
    },
    addSP(state,val){
        console.log('增加商品',val)
        state.spList.push(val)
    },
    addUS(state,username){
        state.username=username
        console.log('js-----'+state.username)
    }
}
const state = {
    carList:[
        {
            name:'苹果',
            price:20,
            num:2
        }
    ],
    spList:[
        {
            name:'苹果',
            price:20
        }
    ],
    username:''
}


export default {
    namespaced:true,
    actions,
    mutations,
    state
}
